//
//  ALPS_TSearchViewController.m
//  Alps
//
//  Created by dllo on 16/6/14.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ALPS_TSearchViewController.h"
#import "ALPS_SearchModel.h"
#import "ALPS_TSearchTCell.h"
#import "TYTabButtonPagerController.h"
#import "ALPS_TSAllDViewController.h"
#import "JXSearchBar+Add.h"
#import "ALPS_TSAlbumDViewController.h"
#import "ALPS_TSVoiceDViewController.h"
#import "ALPS_ClassifyClickClickAlbumController.h"
#import "XLSphereView.h"
@interface ALPS_TSearchViewController ()<UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource, TYPagerControllerDataSource>

@property (nonatomic, strong) UISearchBar *searchBar;
//专辑结果数组
@property (nonatomic, strong) NSMutableArray *dataSource;
//详细搜索头数组
@property (nonatomic, strong) NSMutableArray *topArray;
//搜索结果展示tableView
@property (nonatomic, strong) UITableView *tableView;
//搜索页详细页面View
@property (nonatomic, strong) UIView *detailView;
//辅助搜索页面View
@property (nonatomic, strong) UIView *auxiliaryView;
//分页控制器
@property (nonatomic, strong) TYTabButtonPagerController *pagerController;
//判断是否使用searchBar的text
@property (nonatomic, assign) NSInteger judgerequest;
//记录点击时应该搜索的词汇
@property (nonatomic, copy) NSString *searchString;
//判断是否是第一次进行辅助搜索
@property (nonatomic, assign) NSInteger auxiliary;
//判断是否是第一次进入搜索详细页
@property (nonatomic, assign) NSInteger searchD;

//动画三方
@property (nonatomic,strong) XLSphereView *sphereView;
//三方数组
@property (nonatomic, strong) NSArray *sphereArray;
//三方动画所在View
@property (nonatomic, strong) UIView *sphereV;

@end

@implementation ALPS_TSearchViewController


- (void)dealloc
{
    _tableView.delegate = nil;
    _tableView.dataSource = nil;
    _searchBar.delegate = nil;
    _pagerController.delegate = nil;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.dataSource = [NSMutableArray array];
    self.topArray = [NSMutableArray arrayWithObjects:@"全部", @"专辑", @"声音", nil];
    self.judgerequest = 0;
    self.auxiliary = 0;
    self.searchD = 0;
    [self getView];
    [self getMoreSearchData];
    [self setLeftBackButton];
    NSLog(@"进入搜索页");

}

#pragma mark -- 搜索栏界面
-(void)getView
{
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(70, 15, ScreeWidth - 80, 40)];
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"搜索声音、专辑、人";
    
    //1.设置背景颜色
    //设置背景图去黑线
    self.searchBar.backgroundImage = [[UIImage alloc] init];
    //设置searchBar的颜色主题为白色
    self.searchBar.barTintColor = [UIColor whiteColor];
    
    //2.设置圆角及边框颜色
    UITextField *searchField = [self.searchBar valueForKey:@"searchField"];
    if (searchField) {
        [searchField setBackgroundColor:[UIColor whiteColor]];
        searchField.layer.cornerRadius = 14;
        searchField.layer.borderColor = [UIColor colorWithRed:0.80 green:0.88 blue:0.91 alpha:1.00].CGColor;
        searchField.layer.borderWidth = 1;
        searchField.layer.masksToBounds = YES;
    }
    //3. 设置按钮文字
    [self.searchBar fm_setCancelButtonTitle:@"取消"];
    self.searchBar.tintColor = [UIColor whiteColor];
    [searchField setTintColor:[UIColor orangeColor]];
    
    //4. 设置输入框文字颜色和字体
    [self.searchBar fm_setTextColor:[UIColor blackColor]];
    [self.searchBar fm_setTextFont:[UIFont systemFontOfSize:14]];
    self.navigationItem.titleView = self.searchBar;
    [self.searchBar becomeFirstResponder];

}


#pragma mark -- 三方动画的数据请求以及界面的铺设
-(void)getMoreSearchData
{
    [WSSNetTool GetNetByURL:@"http://mobile.ximalaya.com/m/hot_search_keys?device=iPhone" body:nil headers:nil response:0 success:^(id result) {
        self.sphereV = [[UIView alloc] init];
        self.sphereV.backgroundColor = [UIColor whiteColor];
        self.sphereV.frame = CGRectMake(0, 0, ScreeWidth, ScreeHeight - 64);
        [self.view addSubview:_sphereV];
        
        CGFloat sphereViewW = self.view.frame.size.width - 60 * 2;
        CGFloat sphereViewH = sphereViewW;
        _sphereView = [[XLSphereView alloc] initWithFrame:CGRectMake(60, 20, sphereViewW, sphereViewH)];
        self.sphereArray = [result objectForKey:@"keys"];
        NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:0];
        for (NSInteger i = 0; i < self.sphereArray.count - 2; i ++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
            [btn setTitle:[NSString stringWithFormat:@"%@", self.sphereArray[i]] forState:UIControlStateNormal];
            btn.backgroundColor = [UIColor colorWithRed:arc4random_uniform(255)/255. green:arc4random_uniform(255)/255. blue:arc4random_uniform(255)/255. alpha:1];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            btn.titleLabel.font = [UIFont systemFontOfSize:24.];
            btn.frame = CGRectMake(0, 0, 130, 40);
            btn.tag = 1000 + i;
            btn.layer.cornerRadius = 3;
            btn.clipsToBounds = YES;
            [btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
            [array addObject:btn];
            [_sphereView addSubview:btn];
        }
        [_sphereView setItems:array];
        [self.sphereV addSubview:_sphereView];

    
    } failure:^(NSError *error) {
        
    }];

}


#pragma mark -- 三方动画按钮点击方法
- (void)buttonPressed:(UIButton *)btn
{
    [_sphereView timerStop];
    
    [UIView animateWithDuration:0.3 animations:^{
        btn.transform = CGAffineTransformMakeScale(2., 2.);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3 animations:^{
            btn.transform = CGAffineTransformMakeScale(1., 1.);
        } completion:^(BOOL finished) {
            [_sphereView timerStart];
            NSInteger index = btn.tag - 1000;
            self.searchBar.text = self.sphereArray[index];
            [self searchDetailView];
            [self.searchBar resignFirstResponder];
        }];
    }];
}


#pragma mark -- 编辑文字改变的回调
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self.dataSource removeAllObjects];
    
     [self.tableView reloadData];
    
        if (self.auxiliary == 0) {
            if (searchText != NULL) {
                [self.dataSource removeAllObjects];
                //[self.tableView reloadData];
                [self getShowView];
                [self getClickedData:self.searchBar.text];
                self.judgerequest = 0;
                self.auxiliary = 1;
                
            }
        }
        else
        {
            [self.view bringSubviewToFront:self.auxiliaryView];
            [self.dataSource removeAllObjects];
            [self.tableView reloadData];
            [self getClickedData:self.searchBar.text];
            self.judgerequest = 0;
        }
    if ([searchText isEqualToString:@""]) {
        [self.view bringSubviewToFront:self.sphereV];
    }
    
}

#pragma mark -- 搜索点击方法
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    
    [self searchDetailView];
    [self.searchBar resignFirstResponder];
    
}


#pragma mark -- 搜索详细页面
-(void)searchDetailView
{
    if (self.searchD == 0) {
        self.detailView = [[UIView alloc] init];
        self.detailView.frame = CGRectMake(0, 0, ScreeWidth, ScreeHeight - 64);
        [self.view addSubview:_detailView];
        [self addPagerController];
        self.searchD = 1;
    }else
    {
        [self.view bringSubviewToFront:self.detailView];
        [self.pagerController reloadData];
    }
    
    
}


#pragma mark -- 分页控制器初始化
- (void)addPagerController
{
    TYTabButtonPagerController *pagerController = [[TYTabButtonPagerController alloc]init];
    pagerController.dataSource = self;
    pagerController.adjustStatusBarHeight = YES;
    pagerController.barStyle = TYPagerBarStyleProgressView;
    pagerController.cellSpacing = ScreeWidth  / 3;
    pagerController.progressWidth = 36;
    pagerController.view.frame = self.view.bounds;
    [self addChildViewController:pagerController];
    [self.detailView addSubview:pagerController.view];
    _pagerController = pagerController;
}


#pragma mark - TYPagerControllerDataSource

- (NSInteger)numberOfControllersInPagerController
{
    return self.topArray.count;
}

- (NSString *)pagerController:(TYPagerController *)pagerController titleForIndex:(NSInteger)index
{
    return [self.topArray objectAtIndex:index];
}

- (UIViewController *)pagerController:(TYPagerController *)pagerController controllerForIndex:(NSInteger)index
{
    if (index == 0) {
        //主页
        ALPS_TSAllDViewController *adVC = [[ALPS_TSAllDViewController alloc] init];
        if (self.judgerequest == 0) {
            adVC.searchText = self.searchBar.text;
        }else
        {
            adVC.searchText = self.searchString;
        }
        adVC.Value = ^(NSInteger num)
        {
            if (num) {
                [self.searchBar resignFirstResponder];
            }
        };
        adVC.mobile = ^(NSInteger num)
        {
            [self.pagerController moveToControllerAtIndex:num + 1 animated:YES];
        };
        return adVC;
    }
    //专辑
    else if(index == 1)
    {
        ALPS_TSAlbumDViewController *asdVC = [[ALPS_TSAlbumDViewController alloc] init];
        if (self.judgerequest == 0) {
            asdVC.searchText = self.searchBar.text;
        }else
        {
            asdVC.searchText = self.searchString;
        }
        asdVC.value = ^(NSInteger num)
        {
            if (num) {
                [self.searchBar resignFirstResponder];
            }
        };
        
        return asdVC;
    }
    //声音
    else
    {
        ALPS_TSVoiceDViewController *vdVC = [[ALPS_TSVoiceDViewController alloc] init];
        if (self.judgerequest == 0) {
            vdVC.searchText = self.searchBar.text;
        }
        else
        {
            vdVC.searchText = self.searchString;
        }
        vdVC.value = ^(NSInteger num)
        {
            if (num) {
                [self.searchBar resignFirstResponder];
            }
        };

        return vdVC;
    }
}


#pragma mark -- 辅助搜索的网络请求
-(void)getClickedData:(NSString *)string
{
    [WSSNetTool GetNetByURL:[NSString stringWithFormat:@"http://search.ximalaya.com/suggest?device=iPhone&kw=%@&paidFilter=false",string] body:nil headers:nil response:0 success:^(id result) {
        NSArray *array = [result objectForKey:@"albumResultList"];
        NSArray *arr = [result objectForKey:@"queryResultList"];
        if (self.dataSource.count == 0) {
            for (NSDictionary *dic in array) {
                ALPS_SearchModel *model = [[ALPS_SearchModel alloc] initWithDic:dic];
                [self.dataSource addObject:model];
            }
            for (NSDictionary *dict in arr) {
                ALPS_SearchModel *model = [[ALPS_SearchModel alloc] initWithDic:dict];
                [self.dataSource addObject:model];
            }
        }
        [self.tableView reloadData];
} failure:^(NSError *error) {
         
    }];

    
}

#pragma mark -- 辅助搜索的界面
-(void)getShowView
{
    self.auxiliaryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreeWidth, ScreeHeight - 64)];
    [self.view addSubview:_auxiliaryView];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreeWidth, ScreeHeight - 64) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.auxiliaryView addSubview:_tableView];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ALPS_SearchModel *model = [self.dataSource objectAtIndex:indexPath.row];
    ALPS_TSearchTCell *cell = [[ALPS_TSearchTCell  alloc] init];
    cell.model = [self.dataSource objectAtIndex:indexPath.row];
    cell.string = self.searchBar.text;
    if (model.imgPath != NULL) {
        [cell.thumbnailView sd_setImageWithURL:[NSURL URLWithString:model.imgPath]];
    }
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:model.keyword];
    NSRange rang = [model.keyword rangeOfString:self.searchBar.text];
    [attributedString setAttributes:[NSMutableDictionary dictionaryWithObjectsAndKeys:[UIColor orangeColor], NSForegroundColorAttributeName, nil] range:rang];
    cell.titleLabel.attributedText = attributedString;
    return cell;
}


#pragma mark -- 辅助搜索页点击方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ALPS_SearchModel *model = [self.dataSource objectAtIndex:indexPath.row];
    if (model.imgPath != NULL) {
        ALPS_ClassifyClickClickAlbumController *ccaVC = [[ALPS_ClassifyClickClickAlbumController alloc] init];
        ccaVC.albumId = model.id;
        [self.navigationController pushViewController:ccaVC animated:YES];
    }
    else
    {
        self.searchString = model.keyword;
        self.judgerequest = 1;
        [self searchDetailView];
        [self.searchBar resignFirstResponder];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
